﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace EvertonApp.Data
{
    class LinqRepository<T> : IRepository<T> where T : class, IEntity
    {
        protected Table<T> DataTable;
        protected DataContext Context;
 
        public LinqRepository(DataContext dataContext)
        {
            DataTable = dataContext.GetTable<T>();
            Context = dataContext;
        }
 
        #region IRepository<T> Members
 
        public T Insert(T entity)
        {
            DataTable.InsertOnSubmit(entity);
            try
            {
                Context.SubmitChanges();
            }catch(ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
            return entity;
        }

        bool IRepository<T>.Delete(T entity)
        {
            bool deleteResult = false;
            DataTable.DeleteOnSubmit(entity);
            try
            {
                Context.SubmitChanges();
                deleteResult = true;
            }
            catch (ChangeConflictException e)
            {
                Console.WriteLine(e.Message);
                deleteResult = false;
            }
            return deleteResult;
        }

        public bool Update(Guid id, T entity)
        {
            throw new NotImplementedException();
        }

        public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
        {
            return DataTable.Where(predicate);
        }
 
        public IQueryable<T> GetAll()
        {
            return DataTable;
        }
 
        public T GetById(Guid id)
        {
            // Sidenote: the == operator throws NotSupported Exception!
            // 'The Mapping of Interface Member is not supported'
            // Use .Equals() instead
            return DataTable.Single(e => e.Id.Equals(id));
        }
 
        #endregion
    }
}
